package org.glow.changgou.seckill.consumer;

import com.alibaba.fastjson.JSON;
import org.glow.changgou.seckill.service.SeckillOrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author Glow
 * @Date 2022-10-11 12:17:32
 * @Description 支付状态监听
 * @Version 1.0
 */
@Component
@RabbitListener(queues = "${mq.pay.queue.seckillorder}")
public class SeckillOrderPayMessageListener {
    @Autowired
    private SeckillOrderService seckillOrderService;

    /**
     * 监听消费消息
     * @param message
     */
    @RabbitHandler
    public void consumeMessage(@Payload String message){
        System.out.println(message);
        //将消息转换成Map对象
        Map<String,String> resultMap = JSON.parseObject(message,Map.class);
        System.out.println("监听到的消息:"+resultMap);
        //返回状态码
        String returncode = resultMap.get("return_code");
        String resultcode = resultMap.get("result_code");
        if (returncode.equalsIgnoreCase("success"))
        {
            String outtradeno = resultMap.get("out_trade_no");
            Map<String,String> attachMap = JSON.parseObject(resultMap.get("attach"),Map.class);
            if (resultcode.equalsIgnoreCase("success"))
            {
                seckillOrderService.updatePayStatus(outtradeno,resultMap.get("transaction_id"),attachMap.get("username"));
            }
            else{
                //支付失败,删除订单
                seckillOrderService.closeOrder(attachMap.get("username"));
            }
        }


    }
}